package edu.cuit.zhuyimeng.framework.security.proxy;

import cn.dev33.satoken.dao.SaTokenDaoRedissonJackson;
import cn.hutool.core.util.StrUtil;
import org.redisson.api.RLock;
import org.redisson.api.RReadWriteLock;
import org.redisson.api.RedissonClient;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;

/**
 * SaTokenDaoRedissonJackson动态代理类（执行加锁操作）
 */
public class SaTokenDaoProxy implements InvocationHandler {

    private final RedissonClient redissonClient;
    private final SaTokenDaoRedissonJackson redissonJackson;

    public SaTokenDaoProxy(RedissonClient redissonClient) {
        this.redissonClient = redissonClient;
        redissonJackson = new SaTokenDaoRedissonJackson(redissonClient);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        RReadWriteLock readWriteLock = redissonClient.getReadWriteLock("auth");
        String name = method.getName();
        RLock lock;
        if (name.contains("get") || name.contains("search")) {
            lock = readWriteLock.readLock();
        } else {
            lock = readWriteLock.writeLock();
        }
        lock.lock(5, TimeUnit.SECONDS);
        Object result = method.invoke(redissonJackson, args);
        lock.unlock();
        return result;
    }
}
